package cn.xyfmzmy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        // 模拟线程安全问题
        int[] count = new int[]{1000};
        List<Thread> threads = new ArrayList<>();
        MyLock lock = new MyLock();
        // 100个线程，每个线程让count[0]减10次
        for(int i=0;i<100;i++){
            threads.add(new Thread(()->{
                try{
                    // 获取锁
                    lock.lock();
                    for(int j=0;j<10;j++){
                        Thread.sleep(2);
                        count[0]--;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            }));
        }
        // 启动线程
        for(Thread thread:threads){
            thread.start();
        }
        // 等待线程执行完毕
        for(Thread thread:threads){
            thread.join();
        }
        System.out.println(count[0]);
    }
}
